const fs = require('fs');
const gm = require('gm');
const path = require('path');
const async = require('async');
const fse = require('fs-extra');

//压缩率
const scale_new = 0.5;

//资源路径
const dir_sources = 'E:/client/client_wbqj/assets/resources/gl_zh/';
//输出路径
const dir_out = 'E:/client/client_wbqj/assets/resources/gl_zh/';
//压缩资源配置
let assets_scales = ["ui", 'avatar', "bigBg", "clothe", "common", "commonBG", "commonNew", "commonOld", "commonRes", "emoji", "fightLevel", 'ico',
    "itemproperty", "resIcon", "ruler", "soulmateclothe", "story"];
//不需要压缩的资源
let move_assets = ["blank_spine", "base", "iconAtlas", "materials", "particle", "spine", "font", "effect", "anm", "Ani", "eff", "animation"];


// let assets_scales = ["imgs"];
// let move_assets = ["aaa"];
// const dir_sources = 'C:/Users/chengguoqiang/Desktop/TestForCC/assets/';
// const dir_out = 'C:/Users/chengguoqiang/Desktop/TestForCC/assets/';
// const dir_out = './outRes/';

function loopFiles(dir, callback, type) {
    let stat = fs.statSync(dir);
    if (stat.isDirectory()) {
        let files = fs.readdirSync(dir);
        files.forEach(_f => {
            loopFiles(path.join(dir, _f), callback, type);
        })
    } else if (type.split('|').indexOf(path.extname(dir)) >= 0) {
        callback && callback(dir)
    }
}

/** 是否需要压缩 */
function isScale(path) {
    let bool = false;
    assets_scales.forEach((a) => {
        if (path.includes(a)) {
            bool = true;
            return bool;
        }
    });
    return bool;
}

/** 排除资源 */
function isRemove(path) {
    let bool = false;
    move_assets.forEach((a) => {
        if (path.includes(a)) {
            bool = true;
            return bool;
        }
    });
    return bool;
}

let files = [];
loopFiles(dir_sources, f => {
    console.log("+++++++:", f);
    let _isRemove = isRemove(f);
    if (_isRemove) return;
    let _isScale = isScale(f);
    if (_isScale) {
        files.push(f);
    }
}, '.png|.jpg');

console.log("files:", files.length);

let total = files.length;
let cur = 0;
async.mapLimit(files, 50, (file, callback) => {
    scaleImg(file, scale_new, callback);
}, (err, result) => {
    if (err) {
        console.error("result error");
        console.error(err);
        return;
    }
    console.log('all done')
    fs.writeFileSync('./result.txt', JSON.stringify(result, null, 2))
})


function scaleImg(file, scale, callback) {
    let output = path.join(dir_out, path.relative(dir_sources, file));
    let _odir = path.dirname(output);
    if (!fs.existsSync()) {
        fs.mkdirSync(_odir, { recursive: true });
    }
    let stat = gm(file);
    stat.size((err, size) => {

        let scaledWidth = Math.round(size.width * scale)
        let scaledHeight = Math.round(size.height * scale)

        stat.resize(scaledWidth, scaledHeight).write(output, (err) => {
            if (err) {
                console.error('write error', err);
            } else {
                // console.log(`raw size: ${size.width}*${size.height} scaled: ${scaledWidth}*${scaledHeight}`);
                console.log(cur + '/' + total, ' write done', output)
                changeMate(file, _odir, scaledWidth, scaledHeight);
            }
            cur++;
            // console.log('write:', file);
            callback && callback(err, file);
        })
    })
}

function changeMate(filePath, outPath, width, height) {
    let metaPath = filePath + ".meta";
    const content = fse.readFileSync(metaPath, 'utf8');
    let name = filePath.substr(outPath.length + 1);
    name = name.split(".")[0];
    try {
        obj = JSON.parse(content);
        obj.width = width;
        obj.height = height;
        if (obj.subMetas && obj.subMetas[name]) {
            obj.subMetas[name].width = width;
            obj.subMetas[name].height = height;
            obj.subMetas[name].rawWidth = width;
            obj.subMetas[name].rawHeight = height;
        }
        fse.writeFileSync(metaPath, JSON.stringify(obj, null, 2), 'utf8');
    } catch (error) {
        console.error(`override file error ${filePath}`, error);
    }
}
